import { ButtonNoPadding } from "../../components/lib";
import { useAddTask } from "../../hooks/useTasks";
import { useProjectIdInUrl, useTasksQueryKey } from "./utils";
import { useEffect, useState } from "react";
import { Card, Input, Spin } from "antd";

export const CreateTask = ({ kanbanId }: { kanbanId: number }) => {
  const queryKey = useTasksQueryKey();
  const { mutateAsync: addTask, isLoading } = useAddTask(queryKey);
  const projectId = useProjectIdInUrl();
  const [inputMode, setInputMode] = useState(false);
  const [name, setName] = useState("");

  const toggle = () => setInputMode((mode) => !mode);

  const submit = async () => {
    await addTask({ name, projectId, kanbanId });
    setName("");
  };
  useEffect(() => {
    if (!inputMode) setName("");
  }, [inputMode]);
  return inputMode ? (
    <Spin spinning={isLoading}>
      <Card>
        <Input
          placeholder="新建事务名称"
          onPressEnter={submit}
          value={name}
          onChange={(e) => setName(e.target.value)}
          autoFocus={true}
          onBlur={toggle}
        />
      </Card>
    </Spin>
  ) : (
    <ButtonNoPadding type="link" onClick={toggle}>
      +创建事务
    </ButtonNoPadding>
  );
};
